package com.billow.book.api;

import com.billow.book.utils.SpringContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/test")
public class TestApi {

    @GetMapping("/redisson")
    public void redisson() throws Exception {
        RedissonClient redissonClient = SpringContextUtil.getBean(RedissonClient.class);

        String key = "aaa";

        RLock lock = redissonClient.getLock(key);

        try {
            if (lock.tryLock()) {
                log.info("11111111111111");
                RLock lock2 = redissonClient.getLock(key);
                try {
                    if (lock2.tryLock()) {
                        log.info("22222222222222");
                        RLock lock3 = redissonClient.getLock(key);
                        try {
                            if (lock3.tryLock()) {
                                log.info("3333333333333");
                            }
                        } finally {
                            lock3.unlock();
                        }
                    }
                } finally {
                    lock2.unlock();
                }
            }
        } finally {
            lock.unlock();
        }
        Thread.sleep(1000);
    }

    @GetMapping("/redisson2")
    public void redisson2() throws Exception {
        RedissonClient redissonClient = SpringContextUtil.getBean(RedissonClient.class);

        String key = "aaa";

        RLock lock = redissonClient.getLock(key);

        try {
            if (lock.tryLock()) {
                log.info("11111111111111");
                MyThread thread = new MyThread();
                thread.start();
            }
            Thread.sleep(1000);
        } finally {
            if (lock != null && lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
        }
    }
}
